package com.xhwl.data.util.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.handler.impl.ExcelDataHandlerDefaultImpl;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: JCccc
 * @Description:
 * @Date: Create in 16:23 2021/1/27
 */
@Component
public class ExcelExportUtils {

    @Autowired
    private HttpServletResponse response;
//    @Autowired
//    ObsUtil obsUtil;

    /**
     * 导出excel
     *
     * @param list           泛型数据
     * @param title          标题
     * @param sheetName      sheet的名称
     * @param pojoClass      需要导出的对象
     * @param fileName       文件名称
     * @param isCreateHeader 是否创建表头
     * @throws IOException void
     */
    public void exportExcel(List<?> list, Class<?> pojoClass, String title, String sheetName, String fileName,
                            boolean isCreateHeader) throws IOException {
        final ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
        exportParams.setCreateHeadRows(isCreateHeader);
        baseExport(list, pojoClass, fileName, exportParams);
    }

    /**
     * 导出excel
     *
     * @param list      泛型数据
     * @param title     标题
     * @param sheetName sheet的名称
     * @param pojoClass 需要导出的对象
     * @param fileName  文件名称
     * @throws IOException void
     */
    public void exportExcel(List<?> list, Class<?> pojoClass, String title, String sheetName, String fileName)
            throws IOException {

        ExportParams exportParams = new ExportParams(null, sheetName, ExcelType.HSSF);
        baseExport(list, pojoClass, fileName,exportParams);
    }


    public void exportExcelStream(List<?> list, Class<?> pojoClass, String title, String sheetName, String fileName,HttpServletResponse response)
            throws IOException {
        ExportParams exportParams = new ExportParams(null, sheetName, ExcelType.HSSF);
        baseExportStream(list, pojoClass, fileName,exportParams,response);
    }



    /**
     * 导出excel
     *
     * @param list         泛型数据
     * @param pojoClass    需要导出的对象
     * @param fileName     文件名称
     * @param exportParams 文件参数
     * @throws IOException void
     */
    public void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams)
            throws IOException {
        baseExport(list, pojoClass, fileName, exportParams);
    }

    /**
     * 多个sheet导出
     *
     * @param list
     * @param fileName
     * @throws IOException void
     */
    public void exportExcel(List<Map<String, Object>> list, String fileName) throws IOException {
        baseExport(list, fileName);
    }

    /**
     * 最基础的对象导出
     *
     * @param list         数据列表
     * @param pojoClass    导出对象
     * @param fileName     文件名称
     * @param exportParams 导出文件属性
     * @throws IOException void
     */
    private void baseExport(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams)
            throws IOException {

        final Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, workbook);
    }

    private void baseExportStream(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams,HttpServletResponse response)
            throws IOException {
        final Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        buildExcelDocument( fileName,  workbook,  response);

    }

    private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
        try {
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 导出excel
     *
     * @param list      泛型数据
     * @param title     标题
     * @param sheetName sheet的名称
     * @param pojoClass 需要导出的对象
     * @param fileName  文件名称
     * @throws IOException void
     */
    public String jmUserInfoExportExcel(Short userType, List<?> list, Class<?> pojoClass, String title, String sheetName, String fileName)
            throws IOException {
        String obsUrl = jmBaseExport(userType, list, pojoClass, fileName, new ExportParams(title, sheetName, ExcelType.XSSF));
        return obsUrl;
    }


    /**
     * @param list
     * @param pojoClass
     * @param fileName
     * @throws IOException
     */
    private String jmBaseExport(Short userType, List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams)
            throws IOException {

        exportParams.setStyle(ExcelStyleUtil.class);
//        if (UserInfoTypeEnum.TEACHER_LOGISTICS.getCode() == userType) {
//            exportParams.setTitleHeight((short) 25);
//        }
//
//        final Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
//        Sheet sheet = workbook.getSheetAt(0);
//        Row row = sheet.createRow(0);
//        row.setHeight((short) 3700);
//        Cell cell = row.createCell(0);
//        if (UserInfoTypeEnum.STUDENT.getCode() == userType) {
//            cell.setCellValue("excel字段：\n" +
//                    "\n" +
//                    "校园（必填）；学生姓名（必填）；性别（必填）；学号（必填）；班级（所在年级及班级）；入学时间；\n" +
//                    "学业状态；籍贯（请填写户籍组贯 省市区）；联系号码；证件类型（身份证）；证件号码（不可重复）；居住地（省市区）；详细地址；人脸信息；\n" +
//                    "家长姓名；家长身份；家长性别；联系号码（必填）；证件类型；证件号码；人脸信息；\n" +
//                    "\n" +
//                    "注意事项：\n" +
//                    "\n" +
//                    "（1）导入的单个文档数据不可超过2000条；\n" +
//                    "（2）仅支持xIs/xlsx文件；");
//        }
//        if (UserInfoTypeEnum.TEACHER_LOGISTICS.getCode() == userType) {
//            cell.setCellValue("excel字段：\n" +
//                    "\n" +
//                    "校园（必填）；姓名（必填）；性别（必填）；联系号码（必填，不可重复）；教工工号（注：具备教工身份时，为必填）；证件类型（身份证）；证件号码（不可重复）；居住地（省市区）；\n" +
//                    "是否有后勤身份（必填）；紧急联系人（注：具备后勤身份才填写）；紧急联系人号码（注：具备后勤身份才填写）；\n" +
//                    "\n" +
//                    "注意事项：\n" +
//                    "\n" +
//                    "（1）导入的单个文档数据不可超过2000条；\n" +
//                    "（2）仅支持xIs/xlsx文件；");
//        }
//
//
//        CellStyle cellStyle = workbook.createCellStyle();
//        Font font = workbook.createFont();
//        //字体样式
//        font.setFontName("宋体");
//        //是否加粗
//        font.setBold(false);
//        //字体大小
//        font.setFontHeightInPoints((short) 12);
//        cellStyle.setFont(font);
//        cellStyle.setAlignment(HorizontalAlignment.LEFT);
//        cellStyle.setWrapText(true);//设置自动换行
//        cell.setCellStyle(cellStyle);
//        String saveFileName = fileName + LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
//
//        //转换出字节流数据，调华为云接口上传
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        workbook.write(bos);
//        byte[] byteArray = bos.toByteArray();
//        InputStream inputStream = new ByteArrayInputStream(byteArray);
//        String obsUrl = obsUtil.uploadExcelObs(inputStream, saveFileName);
//
//        System.out.println("excel文件上传华为后返回的数据：" + obsUrl);
//
//        //  downLoadExcel(fileName, workbook);

//        return obsUrl;
return null;

    }

    /**
     * 最基础的多sheet导出
     *
     * @param list     多个不同数据对象的列表
     * @param fileName 文件名称
     * @throws IOException void
     */
    private void baseExport(List<Map<String, Object>> list, String fileName) throws IOException {
        final Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        downLoadExcel(fileName, workbook);
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param workbook exce对象
     * @throws IOException void
     */
    private void downLoadExcel(String fileName, Workbook workbook) throws IOException {
        ServletOutputStream output = null;
        try {
            final String downloadName = URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLS.getValue(), "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + downloadName);
            output = response.getOutputStream();
            workbook.write(output);
        } catch (final Exception e) {
            throw new IOException(e.getMessage());
        } finally {
            if (output != null) {
                output.flush();
                output.close();
            }
        }
    }
}